package services

import (
	dao2 "TaskAssignmentSystem/internal/admin/dao"
	services2 "TaskAssignmentSystem/internal/admin/services"
	"TaskAssignmentSystem/internal/app/dao"
	"fmt"
	"time"
)

type ProjectService struct {
}

func (p *ProjectService) GetCategoryList() (categoryResult []struct {
	Category string `json:"category"`
}, err error) {
	var projectDao dao.Common[dao.SystemProject]
	if err := projectDao.Model().Select("ANY_VALUE(category) as category").Group("category").Find(&categoryResult).Error; err != nil {
		return nil, err
	} else {
		return categoryResult, nil
	}
}

type UserMessage struct {
	CreateDateTime time.Time `json:"create_date_time"`
	Status         int       `json:"status"`
	Content        string    `json:"content"`
}

//项目任务消息

type UserMsgInfo struct {
	dao2.UserMsgInfo
	Content string `json:"content"`
}

func (p *ProjectService) MessageList(page, pageSize int64, projectId string, userid uint) (count int64, result []UserMsgInfo) {
	/*_db := mysql.GetDB()
	_db.Transaction(func(tx *gorm.DB) error {
		var messageServe CommonService[UserMessage]
		messageServe.Page = page
		messageServe.PageSize = pageSize
		messageServe.Order = "tas_user_message.created_at desc"
		messageServe.Query = map[string]interface{}{"project_id": projectId, "system_user_id": userid}
		field := fmt.Sprintf("tas_user_message.created_at as create_date_time,tas_system_msg.content as content,tas_user_message.status as status")
		messageServe.SelectField = &field
		messageServe.LeftJoin = append(messageServe.LeftJoin, fmt.Sprintf("left join tas_system_msg on tas_system_msg.id = tas_user_message.message_id"))
		if res, err := messageServe.SelectList(); err != nil {
			return err
		} else {
			result = res.Data
			count = res.Total
		}
		tx.Model(&dao.UserMessage{}).Where("project_id = ?", projectId).Where("system_user_id = ?", userid).Where("status = 0").Update("status", 1)
		return nil
	})
	return*/

	var messageDao services2.CommonService[UserMsgInfo]
	var userDao dao.Common[dao.SystemUser]
	if user, err := userDao.First(map[string]interface{}{"id": userid}); err != nil {
		return 0, nil
	} else {
		field := fmt.Sprintf("tas_user_msg_info.*,m.content")
		messageDao.SelectField = &field
		messageDao.LeftJoin = append(messageDao.LeftJoin, fmt.Sprintf("left join tas_system_msg m on tas_user_msg_info.msg_id = m.id"))
		messageDao.WhereStr = append(messageDao.WhereStr, fmt.Sprintf("tas_user_msg_info.system_user_id = '%v'", user.UserId))
		//messageDao.WhereStr = append(messageDao.WhereStr, fmt.Sprintf("tas_user_msg_info.status = 0"))
		messageDao.WhereStr = append(messageDao.WhereStr, fmt.Sprintf("m.permissions = '%v'", projectId))
		messageDao.Order = "tas_user_msg_info.id desc"
		messageDao.Page = page
		messageDao.PageSize = pageSize
		if list, err := messageDao.SelectList(); err != nil {
			return 0, nil
		} else {
			if len(list.Data) == 0 {
				return 0, nil
			} else {
				return list.Total, list.Data
			}
		}
	}
}
